package com.shop.utils.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 多线程管理
 */
@Slf4j
@Component
public class ThreadPoolUtils {

    private static final ThreadGroup threadGroup = new ThreadGroup("Thread-Pool-Sport");

    private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            100,
            150,
            1000,
            TimeUnit.MILLISECONDS,
            //阻塞队列
            new ArrayBlockingQueue<>(15),
            //线程新建
            r -> {
                log.info("新建一条线程--{}", Thread.currentThread().getId());
                Thread thread = new Thread(threadGroup, r);
                return thread;
            },
            //拒绝策略
            (r, executor) -> {
                while(true) {
                    try {
                        log.warn("拒绝执行！请等待！");
                        if (executor.getQueue().add(r)) break;
                    } catch (Exception e) {
                        log.error("系统内部出错！{}", e.getCause() + " " + e.getMessage());
                        sleepAndColleteThread(2000);
                    }
                }
            }
    );

    public static <T> void putOperationToThread(Runnable runnable) {
        threadPoolExecutor.execute(runnable);
    }

    public static void sleepAndColleteThread(long timeSleepThread) {
        try {
            Thread.sleep(timeSleepThread);
        } catch (Exception e) {
            log.error("系统线程出错！无法休眠！");
        }
    }
}
